package com.example.lj.uav.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.interfaces.MyOnClickListener;
import com.example.lj.uav.utils.OnUIUtils;
import com.example.lj.uav.adapter.PopupAdapter;
import com.example.lj.uav.view.base.BaseActivity;
import com.example.lj.uav.widget.CommomDialog;
import com.example.lj.uav.widget.CommonPopupWindow;

import dji.common.camera.FocusState;
import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.sdk.base.BaseProduct;
import dji.sdk.camera.Camera;

public class MainActivity extends BaseActivity implements CommonPopupWindow.ViewInterface, View.OnClickListener {

    private CommonPopupWindow popupWindow;
    private FrameLayout fl_menu;
    private View v_menu;
    private RelativeLayout rl_manual;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backToExit();

        fl_menu = findViewById(R.id.main_fl_menu);
        fl_menu.setOnClickListener(this);
        v_menu = findViewById(R.id.main_v_header_menu);
        rl_manual = findViewById(R.id.main_rl_manual);
        rl_manual.setOnClickListener(this);
        findViewById(R.id.main_rl_route).setOnClickListener(this);
        findViewById(R.id.main_v_net).setOnClickListener(this);
        findViewById(R.id.main_v_pic).setOnClickListener(this);

        /**
         * 注册广播接收者以接收设备连接的变化
         */
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyApplication.FLAG_CONNECTION_CHANGE);
        registerReceiver(mReceiver, filter);
//        startService(new Intent(this, FlightRecorderService.class));
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    protected BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            refreshConnectedState();
        }
    };

    private void refreshConnectedState() {
        BaseProduct mProduct = MyApplication.getProductInstance();

        View v_connect_status = findViewById(R.id.main_v_connect_status);
        TextView tv_connect_status = findViewById(R.id.main_tv_connect_status);
        /**
         * 设备状态检查
         */
        if (null != mProduct && mProduct.isConnected()) {

            v_connect_status.setBackgroundResource(R.drawable.ic_point_green);
            if (null != mProduct.getModel()) {
                tv_connect_status.setText(mProduct.getModel().getDisplayName());
            } else {
                tv_connect_status.setText(R.string.unknown_product);
            }
//            initCameraName();
        } else {
            v_connect_status.setBackgroundResource(R.drawable.ic_point_red);
            tv_connect_status.setText(getResources().getString(R.string.disconnected));
            findViewById(R.id.main_ll_lens).setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_fl_menu:
                if (popupWindow == null) {
                    popupWindow = new CommonPopupWindow.Builder(this)
                            .setView(R.layout.popup_down)
                            .setWidthAndHeight(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
//                        .setAnimationStyle(R.style.AnimDown)
                            .setViewOnclickListener(this)
                            .setOutsideTouchable(true)
                            .create();
                    setMeunStatus(true);
                    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            setMeunStatus(false);
                        }
                    });
                }
                if (!popupWindow.isShowing()) {
                    popupWindow.showAsDropDown(fl_menu);
                    setMeunStatus(true);
                }
                break;

            case R.id.main_rl_manual:
                toAct(ManualFlightActivity.class);
                rl_manual.setClickable(false);
                break;
            case R.id.main_rl_route:
                toAct(RouteMenuActivity.class);
                break;
            case R.id.main_v_pic:
//                showToast("main_v_pic");
                //判断是否连接无人机
                if (MyApplication.getProductInstance() == null) {
                    new CommomDialog(this, R.style.commondialog, "飞机未连接，请连接飞机", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(CommomDialog dialog, boolean confirm) {
                            dialog.dismiss();
                        }
                    }).show();
                    return;
                }
                toAct(MediaLibraryActivity.class);
                break;
            case R.id.main_v_net:
                Intent intent = new Intent();
                intent.setClass(this, WebActivity.class);
                intent.putExtra("URL", "http://www.hequavtech.com");
                startActivity(intent);
                break;
        }
    }

    @Override
    public void getChildView(View view, int layoutResId) {
        RecyclerView recycle_view = (RecyclerView) view.findViewById(R.id.pop_down_recycle_view);
        recycle_view.setLayoutManager(new GridLayoutManager(MainActivity.this, 1));
        PopupAdapter mAdapter = new PopupAdapter(MainActivity.this);
        recycle_view.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new MyOnClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (position) {
                    case 0:
                        startActivity(new Intent(MainActivity.this,
                                com.amap.api.maps.offlinemap.OfflineMapActivity.class));
                        break;
                    case 1:
                        toAct(FlightRecordersActivity.class);
                        break;
                    case 2:
                        toAct(DissolutionHistoryActivity.class);
                        break;
                    case 3:
                        toAct(SettingActivity.class);
                        break;
                }
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });

    }

    private void setMeunStatus(boolean isShowing) {
        v_menu.setBackgroundResource(isShowing ? R.drawable.ic_cancel : R.drawable.ic_menu);
    }

    private void initCameraName() {
        /**
         * 相机状态检查
         */
        final Camera camera = MyApplication.getCameraInstance();
        if (camera != null) {
            final LinearLayout ll_lens = findViewById(R.id.main_ll_lens);
            final TextView tv_lens = findViewById(R.id.main_tv_lens);
            camera.setFocusStateCallback(new FocusState.Callback() {
                @Override
                public void onUpdate(@NonNull FocusState focusState) {
                    if (focusState.isLensMounted()) {
                        OnUIUtils.setViewVisibility(ll_lens, View.VISIBLE);
                        if (camera.isInterchangeableLensSupported()) {
                            camera.getLensInformation(new CommonCallbacks.CompletionCallbackWith<String>() {
                                @Override
                                public void onSuccess(String s) {
                                    OnUIUtils.setTextView(tv_lens, s);
                                }

                                @Override
                                public void onFailure(DJIError djiError) {
                                    OnUIUtils.setTextView(tv_lens, getResources().getString(R.string.unknown_product));
                                }
                            });
                        } else {
                            OnUIUtils.setTextView(tv_lens, getResources().getString(R.string.unknown_product));
                        }
                    } else {
                        OnUIUtils.setViewVisibility(ll_lens, View.GONE);
                    }
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        rl_manual.setClickable(true);
    }
}
